package com.example.cloudinterviewdemo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author liuwanxu
 * @date 2025/8/28 14:36
 */
@RestController
public class CpuStressController {
    private volatile boolean isRunning = false;
    private List<Thread> threadList = new ArrayList<>();

    /**
     * 模拟CPU飙升
     * @param numThreads 创建的线程数（建议和CPU核心数相当或更高）
     */
    @GetMapping("/cpu/stress")
    public String stressCpu(@RequestParam(defaultValue = "4") int numThreads) {
        isRunning = true;
        threadList.clear();

        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(() -> {
                // 高强度计算循环，检查标志位以避免无限循环无法停止
                while (isRunning) {
                    // 这里可以进行一些计算，避免空循环被JVM优化掉
                    double value = ThreadLocalRandom.current().nextDouble();
                    Math.log(value); // 执行一些数学运算消耗CPU
                }
            });
            thread.setName("Cpu-Stress-Thread-" + i);
            thread.start();
            threadList.add(thread);
        }
        return "Started " + numThreads + " CPU stress threads.";
    }

    /**
     * 停止CPU压力测试
     */
    @GetMapping("/cpu/stop")
    public String stopCpuStress() {
        isRunning = false;
        // 等待所有线程结束
        for (Thread thread : threadList) {
            try {
                thread.join(1000); // 等待线程结束，最多1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        threadList.clear();
        return "Stopped all CPU stress threads.";
    }
}
